import time
import cv2
import random
# import pyscreeze
import pyscreeze
import win32con
import win32ui
import win32gui
import win32api
import ctypes
import ctypes.wintypes


def screen_desktop(file_name, desk_left, desk_top, desk_width, desk_height):
    # 获取桌面
    desktop = win32gui.GetDesktopWindow()
    # 分辨率适应
    # width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
    # height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
    # left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
    # top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
    # 创建设备描述表
    desktop_dc = win32gui.GetWindowDC(desktop)
    img_dc = win32ui.CreateDCFromHandle(desktop_dc)
    # 创建一个内存设备描述表
    mem_dc = img_dc.CreateCompatibleDC()
    # 创建位图对象
    screenshot = win32ui.CreateBitmap()
    screenshot.CreateCompatibleBitmap(img_dc, desk_width, desk_height)
    mem_dc.SelectObject(screenshot)
    # 截图至内存设备描述表
    mem_dc.BitBlt((0, 0), (desk_width, desk_height), img_dc, (desk_left, desk_top), win32con.SRCCOPY)
    # 将截图保存到文件中
    screenshot.SaveBitmapFile(mem_dc, file_name)
    # 内存释放
    mem_dc.DeleteDC()
    win32gui.DeleteObject(screenshot.GetHandle())


def window_capture(filename):
    hwndDC = win32gui.GetWindowDC(0)  # 0表示当前活跃的窗口
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    saveDC = mfcDC.CreateCompatibleDC()
    saveBitMap = win32ui.CreateBitmap()
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角(l, t)长宽为(w, h)的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)


hwnd = win32gui.FindWindow(None, "动物餐厅")  # 父句柄
hwndChildList = []
win32gui.EnumChildWindows(hwnd, lambda hwnd, param: param.append(hwnd), hwndChildList)
hwnd1 = win32gui.FindWindowEx(hwndChildList[0], 0, None, None)
# win32gui.SetForegroundWindow(hwnd)  # 指定句柄设置为前台，也就是激活
# win32gui.ShowWindow(hwnd, win32con.SW_NORMAL)  # 显示最前 从最小化模式显示为正常
windowRec = win32gui.GetWindowRect(hwnd1)  # 目标子句柄窗口的坐标 左上右下边到屏幕边的距离
# windowRec = get_window_rect(hwnd)
left, top, right, bottom = windowRec[0], windowRec[1], windowRec[2], windowRec[3]
# print(windowRec)
t = random.randint(40, 100) / 100
width, height = windowRec[2] - windowRec[0], windowRec[3] - windowRec[1]


def check_pic(img_name, a, click=False):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    img_path = 'images/{img}.png'.format(img=str(img_name))
    target = cv2.imread(r"%s" % img_path, cv2.IMREAD_GRAYSCALE)
    # 先截图
    # pyscreeze.screenshot('images/animal_screenshot.png', region=(left, top, width, height))
    # animal_screen = ImageGrab.grab(bbox=(left, top, right, bottom))
    # animal_screen.save('images/animal_screenshot.png')
    screen_desktop('images/animal_screenshot.png', left, top, width, height)
    # 读取图片 灰色会快
    temp = cv2.imread(r'images/animal_screenshot.png', cv2.IMREAD_GRAYSCALE)
    tool_height, tool_width = target.shape[:2]
    back_height, back_width = temp.shape[:2]
    # print("目标图宽高：" + str(tool_width) + "-" + str(tool_height))
    # print("模板图宽高：" + str(back_width) + "-" + str(back_height))
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(back_width / screenScale), int(back_height / screenScale)))
    scaling_height, scaling_width = scaleTemp.shape[:2]
    # print("缩放后模板图宽高：" + str(scaling_width) + "-" + str(scaling_height))
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # print(cv2.minMaxLoc(res))
    # cv2.rectangle(temp, max_loc, (max_loc[0] + tool_width, max_loc[1] + tool_height), (0, 0, 225), 2)
    # cv2.imshow("MatchResult----MatchingValue="+str(min_val), temp)
    # cv2.imwrite('1.png', temp, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
    # cv2.waitKey()
    if max_val >= a:
        print("Found it!")
        if not click:
            return True
        else:
            top_left = max_loc
            bottom_right = (top_left[0] + tool_width, top_left[1] + tool_height)
            tagHalfW = int(tool_width / 4)
            tagHalfH = int(bottom_right[1] / 2)
            tagCenterX = top_left[0] + tool_width - tagHalfW
            tagCenterY = int(top_left[1] + 10)
            tmp = [int(tagCenterX), int(tagCenterY)]
            tmp = win32api.MAKELONG(tmp[0], tmp[1])
            win32gui.SendMessage(hwnd1, win32con.WM_ACTIVATE, win32con.WA_CLICKACTIVE, 0)  # 激活窗口
            win32gui.SendMessage(hwnd1, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)  # 鼠标左键按下
            win32gui.SendMessage(hwnd1, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)
            # ctypes.windll.user32.SetCursorPos(tagCenterX, tagCenterY)
            # ctypes.windll.user32.mouse_event(2, 0, 0, 0, 0)
            # ctypes.windll.user32.mouse_event(4, 0, 0, 0, 0)
    else:
        print("%s没找到" % img_name)


def check_share(img_name):
    screenScale = 1
    # 事先读取按钮截图
    img_path = 'images/{img}.png'.format(img=str(img_name))
    target = cv2.imread(r"%s" % img_path, cv2.IMREAD_GRAYSCALE)
    # 先截图
    # pyscreeze.screenshot('images/my_screenshot.png')
    window_capture('images/my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'images/my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    tool_height, tool_width = target.shape[:2]
    back_height, back_width = temp.shape[:2]
    # print("目标图宽高：" + str(tool_width) + "-" + str(tool_height))
    # print("模板图宽高：" + str(back_width) + "-" + str(back_height))
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(back_width / screenScale), int(back_height / screenScale)))
    scaling_height, scaling_width = scaleTemp.shape[:2]
    # print("缩放后模板图宽高：" + str(scaling_width) + "-" + str(scaling_height))
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    # print(cv2.minMaxLoc(res))
    if max_val >= 0.9:
        print("Found it!")
        top_left = max_loc
        bottom_right = (top_left[0] + tool_width, top_left[1] + tool_height)
        tagHalfW = int(tool_width / 4)
        tagHalfH = int(bottom_right[1] / 2)
        tagCenterX = top_left[0] + tool_width - tagHalfW
        tagCenterY = int(top_left[1] + 10)
        ctypes.windll.user32.SetCursorPos(tagCenterX, tagCenterY)
        ctypes.windll.user32.mouse_event(2, 0, 0, 0, 0)
        ctypes.windll.user32.mouse_event(4, 0, 0, 0, 0)
        # win32api.SetCursorPos([tagCenterX, tagCenterY])
        # 左键点击屏幕上的这个位置
        # win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP | win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0)
    else:
        print("没找到")

if __name__ == "__main__":
    start = time.perf_counter()
    # check_pic("share_picture", 0.8)
    # check_share("close_share")
    # check_pic("draw_treasure", 0.9, True)
    # check_pic("gift", 0.9)
    # check_pic("chinese_knot" or "lucky_dog", 0.9)
    # check_pic("visit_friend", 0.8, True)
    # check_share("violet_wait_sow")
    end = time.perf_counter()
    print(end - start)